<?php
namespace com\rs\dns\service;

use com\rs\dns\constant\TokenConstant;
use com\rs\dns\repository\bean\TokenBean;
use com\rs\dns\repository\TokenRepository;
use restphp\utils\RestClassUtils;
use restphp\utils\RestUUIDUtil;

/**
 * Class TokenService
 * @package com\rs\dns\service
 */
final class TokenService {
    /**
     * 创建token
     * @param int $userId
     * @return array
     */
    public static function create($userId) {
        $token = array(
            'token' => RestUUIDUtil::guid(),
            'expireAt' => date('Y-m-d H:i:s', time() + TokenConstant::DEF_EXPIRE_TIME),
            'userId' => $userId
        );
        $tokenRepository = new TokenRepository();
        $tokenRepository->insert($token);
        return array(
            'token' => $token['token'],
            'expireAt' => $token['expireAt']
        );
    }

    /**
     * 删除token.
     * @param $token
     */
    public static function deleteByToken($token) {
        $tokenRepository = new TokenRepository();
        $tokenRepository->delete(array(
            'token' => $token
        ));
    }

    /**
     * token续期.
     * @param $token
     */
    public static function renewal($token) {
        $arrUpdate = array(
            'expireAt' => date('Y-m-d H:i:s', time() + TokenConstant::DEF_EXPIRE_TIME),
        );
        $arrRule = array(
            'token' => $token
        );
        $tokenRepository = new TokenRepository();
        $tokenRepository->update($arrUpdate, $arrRule);
    }

    /**
     * 根据token获取token信息对象
     * @param $token
     * @return TokenBean
     * @throws \restphp\exception\RestException
     */
    public static function getBeanByToken($token) {
        $tokenRepository = new TokenRepository();
        $info = $tokenRepository->findOne(array('token' => $token));
        if (null == $info || empty($info)) {
            return null;
        }
        return RestClassUtils::copyFromArr(new TokenBean(), $info);
    }
}